//
//  AppDelegate.m
//  Commerce
//
//  Created by xiaofeifei on 15/1/30.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "AppDelegate.h"
#import "LeftViewController.h"
#import "RightViewController.h"
#import "HomeViewController.h"
#import "DDMenuController.h"
#import "MobClick.h"
#import "IQKeyboardManager.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "H5ViewController.h"

@interface AppDelegate (){
    BMKMapManager* _mapManager;
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    @try {
        [self initializeAppWithOptions:launchOptions];   //初始化app，包括XcFrame、百度分享、百度地图、统计、推送、支付宝等。
    }
    @catch (NSException *exception) {
        NSLog(@"exception:%@",exception);
    }
    @finally {
        
    }
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    HomeViewController *mainController = [[HomeViewController alloc] init];
    mainController.navStr =@"即时货源";
    mainController.isRootVC = YES;
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mainController];
    navController.navigationBarHidden = YES;

    DDMenuController *rootController = [[DDMenuController alloc] initWithRootViewController:navController];
    _menuController = rootController;
    
    LeftViewController *leftController = [[LeftViewController alloc] init];
    UINavigationController *navLeft = [[UINavigationController alloc] initWithRootViewController:leftController];
    navLeft.navigationBarHidden = YES;
    rootController.leftViewController = navLeft;
    
    RightViewController *rightController = [[RightViewController alloc] init];
    UINavigationController *navRight = [[UINavigationController alloc] initWithRootViewController:rightController];
    navRight.navigationBarHidden = YES;
    rootController.rightViewController = navRight;
    
    self.window.rootViewController = rootController;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;

}

- (void)initializeAppWithOptions:(NSDictionary *)launchOptions {
    //百度地图
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"Lu04j3u68l1okkkh7WEgGAmz"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //消息推送机制
    [[XCPushHandler sharedPushHandler] setPushDelegate:self];
    [[XCPushHandler sharedPushHandler] configPushWithOptions:launchOptions];
    
    //键盘检测
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    
    //友盟分享
    [UMSocialData setAppKey:UMENG_APPKEY];
    //友盟统计
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    [MobClick startWithAppkey:UMENG_APPKEY reportPolicy:(ReportPolicy) BATCH channelId:nil];
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wxdb0b5dd2066c88f5" appSecret:@"01fec2f5d84adf67d76ce710d29f657e" url:@"http://www.zhi56.cn/home/ld"];
    
    [[GlobalData sharedGlobalData] getData];
    
    [self getVersion];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"VERSON1.3"] boolValue] == NO) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"VERSON1.3"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SpecificationData"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"TypeData"];
    }
  
}

//更新app
- (void)updateAppWithUrl{
    NSString *urlStr = @"https://itunes.apple.com/us/app/dou-dao-wu-liu-bai-shi-tong/id1004219890?l=zh&ls=1&mt=8";
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"hasShownGuideImgs"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
}

- (void)getVersion
{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@/sys/version",URL_ROOT]
                                    params:nil
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [SVProgressHUD dismiss];
                                  NSLog(@"responseObject=%@",result);
                                  [SVProgressHUD dismiss];
                                  NSLog(@"JSON: %@", responseObject);
                                  
                                  NSArray *versionList = [[NSUserDefaults standardUserDefaults] objectForKey:@"versionList"];
                                  if (versionList.count == 0) {
                                      [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"versionList"];
                                  }else{
                                      for (int i=0; i< versionList.count; i++) {
                                          NSInteger oldID = [versionList[i][@"ID"] integerValue];
                                          NSInteger newID = [responseObject[i][@"ID"] integerValue];
                                          if (oldID == newID) {
                                              float versionOld = [versionList[i][@"Version"] integerValue];
                                              float versionNew = [responseObject[i][@"Version"] integerValue];
                                              if (versionNew > versionOld) {
                                                  switch (oldID) {
                                                      case 1:
                                                          [[GlobalData sharedGlobalData] setIsNewLeft:YES];
                                                          [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"versionList"];
                                                          break;
                                                      case 2:
                                                          [[GlobalData sharedGlobalData] setIsNewRight:YES];
                                                          [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"versionList"];
                                                          break;
                                                      case 3:
                                                          [[GlobalData sharedGlobalData] setIsNewArea:YES];
                                                          [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"versionList"];
                                                          break;
                                                      case 5:
                                                      {
                                                          [[GlobalData sharedGlobalData] setIsNewVersion:YES];
                                                          [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"versionList"];
                                                          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"有新版本发布了，是否升级？" delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"立即更新", nil];
                                                          [alert showWithCompletionHandler:^(NSInteger buttonIndex) {
                                                              if (buttonIndex==1) {
                                                                  [self updateAppWithUrl];
                                                              }
                                                          }];
                                                      }
                                                          break;
                                                      default:
                                                          break;
                                                  }
                                              }else{
                                                  switch (oldID) {
                                                      case 1:
                                                          [[GlobalData sharedGlobalData] setIsNewLeft:NO];
                                                          break;
                                                      case 2:
                                                          [[GlobalData sharedGlobalData] setIsNewRight:NO];
                                                          break;
                                                      case 3:
                                                          [[GlobalData sharedGlobalData] setIsNewArea:NO];
                                                          break;
                                                      case 5:
                                                          [[GlobalData sharedGlobalData] setIsNewVersion:NO];
                                                          break;
                                                      default:
                                                          break;
                                                  }
                                              }
                                              
                                          }
                                      }
                                  }
                                  
                              }];

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}

#pragma mark -
#pragma mark push methods
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[XCPushHandler sharedPushHandler] didRegisterDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[XCPushHandler sharedPushHandler] receivePushWithData:userInfo];
}

- (void)pushToTargetWithInfo:(NSDictionary *)userInfo {
    NSLog(@"%@",userInfo);
    H5ViewController *vc = [[H5ViewController alloc] initWithNibName:nil bundle:nil];
    vc.urlStr = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
    UINavigationController *navController = (UINavigationController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [navController pushViewController:vc animated:YES];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
